package top.itaso.lib.widget.helper;

import android.util.Log;
import android.view.View;

import androidx.annotation.IdRes;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import top.itaso.lib.widget.vo.Node;

/**
 * @Description:
 * @Author itsdf07
 * @E-Mail 923255742@qq.com
 * @Gitee https://gitee.com/itsdf07
 * @Date 2021/12/5
 */
public abstract class NodeTreeBaseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final String TAG = this.getClass().getSimpleName();
    /**
     * 0-默认不展开
     */
    private int defaultExpandLevel = 0;

    /**
     * Item 展开的示意图片资源，如向上箭头
     */
    @IdRes
    private int iconExpand = -1;
    /**
     * Item 非展开的示意图片资源，如向下箭头
     */
    @IdRes
    private int iconUnExpand = -1;

    /**
     * 存储所有的 Node
     */
    private List<Node> mAllNodes;

    /**
     * 存储所有可见的 Node
     */
    private List<Node> mVisibleNodes;

    /**
     * 点击的回调接口
     */
    private INodeTreeClickListener iNodeTreeClickListener;

    /**
     * 节点点击事件回调
     *
     * @param <T>
     */
    public interface INodeTreeClickListener<T> {
        void onClick(Node<T> node, int position);
    }

    public void setOnNodeTreeClickListener(INodeTreeClickListener listener) {
        this.iNodeTreeClickListener = listener;
    }

    /**
     * @param sourceNodes        所有节点数据
     * @param defaultExpandLevel 默认展开几级树
     */
    public NodeTreeBaseAdapter(List<Node> sourceNodes, int defaultExpandLevel) {
        this(sourceNodes, defaultExpandLevel, -1, -1);
    }

    /**
     * @param sourceNodes        所有节点数据
     * @param defaultExpandLevel 默认展开几级树
     * @param iconExpand         展开的示意图片资源，如向上箭头
     * @param iconUnExpand       非展开的示意图片资源，如向下箭头
     */
    public NodeTreeBaseAdapter(List<Node> sourceNodes, int defaultExpandLevel, @IdRes int iconExpand, @IdRes int iconUnExpand) {
        this.defaultExpandLevel = defaultExpandLevel;
        this.iconExpand = iconExpand;
        this.iconUnExpand = iconUnExpand;

        for (Node node : sourceNodes) {
            node.getChildren().clear(); //此处为初始化数据，为了确保层级数据的正确定，对每个节点关联的数据先进行一次清空，确保不存在之前的数据
            node.setIndicativeIconExpand(iconExpand);
            node.setIndicativeIconUnExpand(iconUnExpand);
        }

        /**
         * 对所有的Node进行排序
         */
        mAllNodes = NodeTreeHelper.convertNodes(sourceNodes, defaultExpandLevel);

        /**
         * 过滤出可见的Node
         */
        mVisibleNodes = NodeTreeHelper.filterVisibleNodes(mAllNodes);
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        Node node = mVisibleNodes.get(position);
        //        convertView = getConvertView(node, position, convertView, parent);
        // 设置内边距
        holder.itemView.setPadding(node.getLevel() * 50, 10, 10, 10);
        /**
         * 设置节点点击时，可以展开以及关闭,将事件继续往外公布
         */
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: >>>>>>position=" + position + ",title=" + node.getTitle());
                expandOrCollapse(node);
                if (iNodeTreeClickListener != null) {
                    iNodeTreeClickListener.onClick(node, position);
                }
            }
        });
        onBindViewHolder(node, holder, position);
    }

    @Override
    public int getItemCount() {
        return mVisibleNodes.size();
    }


    /**
     * 获取排序后所有节点
     *
     * @return
     */
    public List<Node> getAllNodes() {
        if (mAllNodes == null) {
            mAllNodes = new ArrayList<Node>();
        }
        return mAllNodes;
    }

    /**
     * 获取所有选中节点
     *
     * @return
     */
    public List<Node> getSelectedNode() {
        List<Node> checks = new ArrayList<Node>();
        for (int i = 0; i < mAllNodes.size(); i++) {
            Node n = mAllNodes.get(i);
            if (n.isChecked()) {
                checks.add(n);
            }
        }
        return checks;
    }


    /**
     * 设置多选
     *
     * @param node
     * @param checked
     */
    public void setChecked(final Node node, boolean checked) {
        node.setChecked(checked);
        setChildChecked(node, checked);
        if (node.getParent() != null) {
            setNodeParentChecked(node.getParent(), checked);
        }
        notifyDataSetChanged();
    }

    /**
     * 清除掉之前数据并刷新  重新添加
     *
     * @param sourceNodes
     * @param defaultExpandLevel 默认展开几级列表
     */
    public void refreshAllNode(List<Node> sourceNodes, int defaultExpandLevel) {
        mAllNodes.clear();
        addData(-1, sourceNodes, defaultExpandLevel);
    }

    /**
     * 在指定位置添加数据并刷新 可指定刷新后显示层级
     *
     * @param index
     * @param sourceNodes
     * @param defaultExpandLevel 默认展开几级列表
     */
    public void addData(int index, List<Node> sourceNodes, int defaultExpandLevel) {
        this.defaultExpandLevel = defaultExpandLevel;
        notifyData(index, sourceNodes);
    }

    /**
     * 在指定位置添加数据并刷新
     *
     * @param index
     * @param sourceNodes
     */
    public void addData(int index, List<Node> sourceNodes) {
        notifyData(index, sourceNodes);
    }

    /**
     * 添加数据并刷新
     *
     * @param sourceNodes
     */
    public void addData(List<Node> sourceNodes) {
        addData(sourceNodes, defaultExpandLevel);
    }

    /**
     * 添加数据并刷新 可指定刷新后显示层级
     *
     * @param sourceNodes
     * @param defaultExpandLevel
     */
    public void addData(List<Node> sourceNodes, int defaultExpandLevel) {
        this.defaultExpandLevel = defaultExpandLevel;
        notifyData(-1, sourceNodes);
    }

    /**
     * 添加数据并刷新
     *
     * @param node
     */
    public void addData(Node node) {
        addData(node, defaultExpandLevel);
    }

    /**
     * 添加数据并刷新 可指定刷新后显示层级
     *
     * @param node
     * @param defaultExpandLevel
     */
    public void addData(Node node, int defaultExpandLevel) {
        List<Node> nodes = new ArrayList<>();
        nodes.add(node);
        this.defaultExpandLevel = defaultExpandLevel;
        notifyData(-1, nodes);
    }


    public abstract void onBindViewHolder(Node node, RecyclerView.ViewHolder holder, final int position);


    /**
     * 相应ListView的点击事件 展开或关闭某节点
     *
     * @param node
     */
    private void expandOrCollapse(Node node) {
        if (node != null) {// 排除传入参数错误异常
            if (!node.isLeaf()) {
                node.setExpand(!node.isExpand());
                mVisibleNodes = NodeTreeHelper.filterVisibleNodes(mAllNodes);
                notifyDataSetChanged();// 刷新视图
            }
        }
    }

    /**
     * 设置是否选中
     *
     * @param node
     * @param checked
     */
    private <T> void setChildChecked(Node<T> node, boolean checked) {
        if (!node.isLeaf()) {
            node.setChecked(checked);
            for (Node childrenNode : node.getChildren()) {
                setChildChecked(childrenNode, checked);
            }
        } else {
            node.setChecked(checked);
        }
    }

    private void setNodeParentChecked(Node node, boolean checked) {
        if (checked) {
            node.setChecked(true);
        } else {
            List<Node> childrens = node.getChildren();
            boolean isChecked = false;
            for (Node children : childrens) {
                if (children.isChecked()) {
                    isChecked = true;
                }
            }
            //如果所有自节点都没有被选中 父节点也不选中
            if (!isChecked) {
                node.setChecked(false);
            }
        }
        if (node.getParent() != null) {
            setNodeParentChecked(node.getParent(), checked);
        }
    }

    /**
     * 刷新数据
     *
     * @param index
     * @param sourceNodes
     */
    private void notifyData(int index, List<Node> sourceNodes) {
        for (int i = 0; i < sourceNodes.size(); i++) {
            Node node = sourceNodes.get(i);
            node.getChildren().clear();
            node.setIndicativeIconExpand(iconExpand);
            node.setIndicativeIconUnExpand(iconUnExpand);
        }
        for (int i = 0; i < mAllNodes.size(); i++) {
            Node node = mAllNodes.get(i);
            node.getChildren().clear();
            // node.isNewAdd = false;
        }
        if (index != -1) {
            mAllNodes.addAll(index, sourceNodes);
        } else {
            mAllNodes.addAll(sourceNodes);
        }
        /**
         * 对所有的Node进行排序
         */
        mAllNodes = NodeTreeHelper.convertNodes(mAllNodes, defaultExpandLevel);
        /**
         * 过滤出可见的Node
         */
        mVisibleNodes = NodeTreeHelper.filterVisibleNodes(mAllNodes);
        //刷新数据
        notifyDataSetChanged();
    }
}
